package com.winona.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.taplinker.client.AppConfigFactory;
import com.taplinker.client.R;
import com.taplinker.client.core.ImageManager;
import com.taplinker.client.domain.UserInfo;
import com.taplinker.core.rpc.Result;
import com.taplinker.core.rpc.command.SimpleBaseCommand;
import com.taplinker.core.rpc.http.HttpTemplate;
import com.taplinker.core.util.json.JsonUtil;
import com.winona.Base1Activity;
import com.winona.ConstantValue;
import com.winona.bean.Paper;
import com.winona.code.ReserveCmd;
import com.winona.widget.PullToRefreshView;

@SuppressLint({ "ResourceAsColor", "HandlerLeak" })
public class AcademicActivitiesActivity extends Base1Activity {
	private TextView noreservations;

	final int SHOW_DIALOG = 1;

	private int PAGE_SIZE = 10;
	private TextView title;
	private ImageView back;
	private Intent intent;
	private PullToRefreshView mRefreshView;
	private ListView listView;
	private BaseAdapter mAdapter;

	private boolean isClear = false;

	private int gotopage = 1;
	private Paper paper;

	private List<Paper> paperList = null;
	private boolean hasMore = true;

	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			try {
				int position = msg.what;

				paperList.get(position).setStatus("NOTVERFIED");

				mAdapter.notifyDataSetChanged();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	};

	private UserInfo user = AppConfigFactory.getInstance().getUserInfo();

	// public final static String STATUS_VERFIED = "VERFIED"; // 审核通过
	// public final static String STATUS_REJECT = "REJECT"; //审核未通过
	// public final static String STATUS_NOTVERFIED = "NOTVERFIED"; //未审核

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.inport_news);

		findView();

		setLinstener();
		init();
		getData();

	}

	private void init() {
		title.setText("学术活动");
		paperList = new ArrayList<Paper>();
		mRefreshView.disableScroolDown();
		mRefreshView.enableScroolUp();
		mRefreshView
				.setOnFooterRefreshListener(new PullToRefreshView.OnFooterRefreshListener() {

					@Override
					public void onFooterRefresh(PullToRefreshView view) {
						getData();
					}
				});

	}

	private void getData() {
		if (!hasMore) {
			Toast.makeText(getApplicationContext(), "没有了", Toast.LENGTH_SHORT)
					.show();
			mRefreshView.onFooterRefreshComplete();
			return;
		}

		new SimpleBaseCommand() {

			@Override
			public Result go() {
				int gotopage = 1;
				if (paperList != null && paperList.size() > PAGE_SIZE) {
					gotopage = paperList.size() / PAGE_SIZE;
					if (paperList.size() % PAGE_SIZE > 0) {
						gotopage += 1;
					}
				}
				return new HttpTemplate().exchange(ConstantValue.COMMON
						+ "/academic/project/finds?academicid=2&gotopage="
						+ gotopage + "&pagesize=" + PAGE_SIZE
						+ "&role=EXPERT&userid=" + user.getUserid());
			}

			@Override
			public void no(Result result) {
				mRefreshView.onFooterRefreshComplete();
			}

			@Override
			public void yes(Result result) {
				mRefreshView.onFooterRefreshComplete();
				String json = result.object.toString();
				if (StringUtils.isNotEmpty(json)) {
					try {
						org.json.JSONObject jo = new org.json.JSONObject(json);
						String jstr = null;
						jstr = jo.getString("body");
						paperList = JsonUtil.jsonToList(jstr, Paper.class);

					} catch (JSONException e) {
						e.printStackTrace();
					}
				}

				if (mAdapter == null) {
					mAdapter = new PaperAdapter();
					listView.setAdapter(mAdapter);
				} else {
					mAdapter.notifyDataSetChanged();
				}
			}

		}.execute();

	}

	private void findView() {

		title = (TextView) findViewById(R.id.inport_title);
		back = (ImageView) findViewById(R.id.inport_back);
		listView = (ListView) findViewById(R.id.inport_list_view);
		mRefreshView = (PullToRefreshView) findViewById(R.id.pull_refresh_view);
		listView.setCacheColorHint(0);

	}

	private void setLinstener() {

		back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				startActivity(AcademicCenterActivity.class);
			}
		});
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				HashMap<String, Object> map = new HashMap<String, Object>();
				map.put("Academic", paperList.get(position));

				startActivity(ActivityNameActivity.class, map);

			}

		});

	}

	private void showMyDialog(final int position) {
		final AlertDialog mDialog = new AlertDialog.Builder(this).create();
		View dialog = LayoutInflater.from(AcademicActivitiesActivity.this)
				.inflate(R.layout.bookmark_input, null);
		final TextView userName = (TextView) dialog.findViewById(R.id.et_name);
		final TextView userEmil = (TextView) dialog.findViewById(R.id.et_emil);
		Button ok = (Button) dialog.findViewById(R.id.bjhmcOk);
		Button cancel = (Button) dialog.findViewById(R.id.bjhmcCancle);

		ok.setOnClickListener(new android.view.View.OnClickListener() {
			@Override
			public void onClick(View v) { // 预约
				new ReserveCmd(AcademicActivitiesActivity.this, userName
						.getText().toString(), userEmil.getText().toString(),
						mHandler, paperList.get(position).getAcademicProject()
								.getId()).execute();
				mDialog.dismiss();

			}

		});
		cancel.setOnClickListener(new android.view.View.OnClickListener() {
			@Override
			public void onClick(View v) { // 关闭对话框
				mDialog.dismiss();
			}
		});
		mDialog.setView(dialog);
		mDialog.show();
	}

	private class PaperAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return paperList.size();
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			View view = View.inflate(getApplicationContext(),
					R.layout.activity_item, null);
			ImageView iv_logo = (ImageView) view
					.findViewById(R.id.activity_img);
			TextView tv_name = (TextView) view.findViewById(R.id.activity_name);
			TextView content = (TextView) view.findViewById(R.id.activity_des);
			View new_img = view.findViewById(R.id.new_img);
			View yuyue = view.findViewById(R.id.activity_yuyue);
			TextView noreservations = (TextView) view
					.findViewById(R.id.activity_noreservations);

			if (position < 1) {
				new_img.setVisibility(View.VISIBLE);
			} else {
				new_img.setVisibility(View.GONE);
			}

			// 如果可以预约
			boolean is = paperList.get(position).getAcademicProject()
					.isOrderable();
			if (is == true) {
				yuyue.setVisibility(View.VISIBLE);
				String status = paperList.get(position).getStatus();
				if (status == null) {
					noreservations.setText("未预约");
					noreservations
							.setBackgroundResource(R.drawable.center_noyuyue);

				} else if (status.equals("VERFIED")) {
					noreservations.setText("已预约");
					noreservations.setTextColor(R.color.isyuyue);
					noreservations
							.setBackgroundResource(R.drawable.center_isyuyue);
					noreservations.setClickable(false);

				} else if (status.equals("NOTVERFIED")) {
					noreservations.setText("审核中");
					noreservations.setTextColor(R.color.yuyueing);
					noreservations
							.setBackgroundResource(R.drawable.center_yuyueing);
					noreservations.setClickable(false);

				}
			} else {
				noreservations.setVisibility(View.GONE);
				yuyue.setVisibility(View.GONE);
			}

			noreservations.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					showMyDialog(position);
				}

			});

			tv_name.setText(paperList.get(position).getAcademicProject()
					.getName());
			content.setText(paperList.get(position).getAcademicProject()
					.getContentName());
			if (!TextUtils.isEmpty(paperList.get(position).getAcademicProject()
					.getImageUrl())) {
				ImageManager.getInstance().loadImage(
						ConstantValue.IMAGE
								+ paperList.get(position).getAcademicProject()
										.getImageUrl(), iv_logo, 60, 60, null);
			}

			return view;
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

	}

}
